<template>
  <div class="m-8">
    <SearchDemo
      v-model="searchName"
      placeholder="用户名"
      @searchInput="searchInput('user')"
      @claerInput="claerInput('user')"
    />
    <div>
      <el-button id="b3" type="primary" class="px-4 py-2 mt-8" @click="openAddDialog('user')">
        添加
      </el-button>
      <el-dialog
        v-model="addBox"
        :title="dialogTitle"
        width="500"
        align-center
        @close="handleClose"
      >
        <el-form :model="form" label-width="auto" ref="formRef">
          <el-form-item
            label="用户名："
            prop="inputname"
            :rules="{
              required: true,
              message: '用户名不可为空',
              trigger: 'blur'
            }"
          >
            <el-input v-model="form.inputname" placeholder="用户名" clearable />
          </el-form-item>
          <el-form-item
            label="密码："
            prop="inputpassword"
            :rules="{
              required: true,
              message: '用户密码不可为空',
              trigger: 'blur'
            }"
          >
            <el-input v-model="form.inputpassword" type="password" placeholder="密码" clearable />
          </el-form-item>
          <el-form-item label="昵称：">
            <el-input v-model="inputnickName" placeholder="昵称" clearable />
          </el-form-item>
          <el-form-item label="邮箱：">
            <el-input v-model="inputemail" placeholder="邮箱" clearable />
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="inputnote" placeholder="备注" clearable />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleClose" class="px-4 py-2 mr-3"> 取消 </el-button>
            <el-button type="primary" @click="submit(formRef)"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <el-table
      :data="tableData"
      stripe
      class="w-full mt-2"
      border
      :header-cell-style="{ 'text-align': 'center', height: '60px' }"
      :cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column prop="id" label="编号" width="150px" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="nickName" label="昵称" />
      <el-table-column prop="email" label="邮箱" width="500px" />
      <el-table-column prop="note" label="备注" />

      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            type="primary"
            class="!p-2 text-base font-bold"
            text
            visible="false"
            @click="openEditDialog(row)"
          >
            编辑
          </el-button>

          <el-button
            type="danger"
            class="!p-2 text-base font-bold"
            text
            visible="false"
            @click="delusers(row)"
          >
            删除
          </el-button>

          <el-button
            type="success"
            class="!p-2 text-base font-bold"
            text
            visible="false"
            @click="showDrawer(row)"
          >
            分配角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-drawer title="分配角色" v-model="drawer" size="20%">
    <div>
      <el-checkbox-group v-model="checkList">
        <div class="flex flex-col">
          <el-checkbox
            v-for="item in roleData"
            :key="item.value"
            :label="item.name"
            :value="item.id"
          />
        </div>
      </el-checkbox-group>
    </div>
    <template #footer>
      <div class="drawer-footer">
        <el-button type="primary" @click="giveRole"> 确定 </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { createOneUser, delUser, getUserRole, updataUserRole, upDateUser } from '@/api/role'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { reactive, ref } from 'vue'
import SearchDemo from './components/SearchDemo.vue'
import { useTable } from '@/composables/useTable'

let {
  tableData,
  getTableData,
  roleData,
  getRole,
  claerInput,
  searchName,
  searchInput,
  openAddDialog,
  isAdd,
  addBox,
  dialogTitle,
  drawer
} = useTable()

const inputemail = ref('')
const inputnickName = ref('')
const inputnote = ref('')
const formRef = ref<FormInstance>()

let editId = 0
let adminId = 0
let checkList = ref<any[]>([])

const form = reactive({
  inputname: '',
  inputpassword: ''
})

//获取所有用户信息
getTableData('user')

//打开编辑弹窗
function openEditDialog(row: {
  id: any
  username: any
  email: any
  note: any
  password: any
  nickName: any
}) {
  addBox.value = true
  dialogTitle.value = '编辑用户'
  isAdd.value = false
  form.inputname = row.username
  form.inputpassword = row.password
  inputemail.value = row.email
  inputnickName.value = row.nickName
  inputnote.value = row.note
  editId = row.id
}

//弹窗确认添加用户或编辑用户
const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (isAdd.value) {
        createUser()
      } else {
        updateUser()
      }
    }
  })
}

//关闭弹窗
const handleClose = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  form.inputname = ''
  form.inputpassword = ''
  inputemail.value = ''
  inputnickName.value = ''
  inputnote.value = ''
  addBox.value = false
}

//新增一条用户信息
async function createUser() {
  const data = {
    username: form.inputname,
    email: inputemail.value,
    note: inputnote.value,
    password: form.inputpassword,
    nickName: inputnickName.value
  }
  await createOneUser(data)
  getTableData('user')
  handleClose()
}

//编辑指定用户信息
async function updateUser() {
  const id = editId
  const data = {
    username: form.inputname,
    email: inputemail.value,
    note: inputnote.value,
    password: form.inputpassword,
    nickName: inputnickName.value
  }
  await upDateUser(id, data)
  getTableData('user')
  handleClose()
}

//删除一条用户信息
function delusers(row: { id: any }) {
  ElMessageBox.confirm('确定要删除此条用户信息吗？', '注意', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    cancelButtonClass: 'cancel-btn',
    type: 'warning',
    center: true
  })
    .then(async () => {
      await delUser(row.id)
      ElMessage({
        type: 'success',
        message: '成功删除'
      })
      claerInput('user')
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

/**
 * 打开分配角色抽屉、获取当前用户id的角色信息
 */
async function showDrawer(row: { id: any }) {
  getRole()
  drawer.value = true
  adminId = row.id
  const data = await getUserRole(adminId)
  const newdata = data.data
  const idArray = newdata.map((i: { id: any }) => {
    return i.id
  })
  checkList.value = idArray
}

/**
 * 分配角色
 */
async function giveRole() {
  const params = {
    adminId: adminId,
    roleIds: checkList.value.join()
  }
  await updataUserRole(params)
  drawer.value = false
  ElMessage({
    message: '分配成功',
    type: 'success'
  })
}
</script>

<style scoped></style>
